package com.duowei.diandan.fragment;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ImageView;

import com.duowei.diandan.R;
import com.duowei.diandan.activity.WelcomeActivity;
import com.duowei.diandan.adapter.CateAdapter;
import com.duowei.diandan.adapter.MenuAdapter;
import com.duowei.diandan.app.OrderList;
import com.duowei.diandan.bean.food.FoodImpl;
import com.duowei.diandan.bean.food.FoodItem;
import com.duowei.diandan.bean.food.Meal;
import com.duowei.diandan.bean.food.Single;
import com.duowei.diandan.bean.food.SingleAndMeals;
import com.duowei.diandan.bean.food.SingleGroup;
import com.duowei.diandan.constant.ChoiceType;
import com.duowei.diandan.constant.OrderMode;
import com.duowei.diandan.constant.Settings;
import com.duowei.diandan.databinding.MenuFragmentBinding;
import com.duowei.diandan.db.FoodMenu;
import com.duowei.diandan.event.ToastEvent;
import com.duowei.diandan.fragment.dialog.PromptDialogFragment;
import com.duowei.diandan.util.AnimHelper;

import org.greenrobot.eventbus.EventBus;

import java.util.Locale;
import java.util.Observer;

public class MenuFragment extends BaseFragment implements MenuAdapter.OnFoodItemClickListener {
    public static final String TAG = "MenuFragment";

    private MenuFragmentBinding mBinding;
    private GridLayoutManager mLayoutManager;
    private CateAdapter mCateAdapter;
    private MenuAdapter mMenuAdapter;

    private Observer mOrderListObserver = (o, arg) -> {
        int size = OrderList.getInstance().getOrderItemList().size();
        if (size > 0) {
            if (Settings.ORDER_MODE == OrderMode.COMMIT) {
                mBinding.cartButton.setText(String.format(Locale.CHINA, "查看订单(%d)", size));

            } else {
                mBinding.cartButton.setText(String.format(Locale.CHINA, "购物车(%d)", size));
            }

        } else {
            if (Settings.ORDER_MODE == OrderMode.COMMIT) {
                mBinding.cartButton.setText("查看订单");

            } else {
                mBinding.cartButton.setText("购物车");
            }
        }
    };

    private Observer mCateObserver = (o, arg) -> {
        getHandler().post(() -> {
            if (mCateAdapter != null) {
                mCateAdapter.updateData(FoodMenu.getInstance().getAllFoodCate());
            }
        });
    };

    private Observer mMenuObserver = (o, arg) -> {
        getHandler().post(() -> {
            if (mMenuAdapter != null) {
                mMenuAdapter.updateData(FoodMenu.getInstance().getAllFoodItem());
            }
        });
    };

    private RecyclerView.OnScrollListener mOnScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);

            if (mMenuAdapter != null && dy != 0) {
                int pos;

                if (dy > 0) {
                    pos = mLayoutManager.findLastCompletelyVisibleItemPosition();
                } else {
                    pos = mLayoutManager.findFirstCompletelyVisibleItemPosition();
                }

                if (pos != -1) {
                    FoodItem item = mMenuAdapter.getList().get(pos);

                    int catePosition = FoodMenu.getInstance().getCatePosition(item.getCateUuid());
                    if (catePosition != -1) {
                        Log.d(TAG, "onScrolled: CatePosition = " + catePosition);

                        mBinding.cateListView.smoothScrollToPosition(catePosition);
                        mBinding.cateListView.setItemChecked(catePosition, true);
                    }
                }
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_menu, container, false);

        // 顶部搜索
        if (Settings.ORDER_MODE == OrderMode.COMMIT && Settings.SEARCH_BAR_ENABLE) {
            mBinding.searchLayout.setVisibility(View.VISIBLE);
            mBinding.searchEditText.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    if (mMenuAdapter != null) {
                        mMenuAdapter.getFilter().filter(s);
                    }
                }

                @Override
                public void afterTextChanged(Editable s) {
                }
            });

            mBinding.searchCloseView.setOnClickListener(v -> {
                cleanSearchText();
            });

        } else {
            mBinding.searchLayout.setVisibility(View.GONE);
        }

        // 分类
        mCateAdapter = new CateAdapter(getContext(), FoodMenu.getInstance().getAllFoodCate(), mBinding.cateListView);
        mBinding.cateListView.setAdapter(mCateAdapter);

        mBinding.cateListView.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
        mBinding.cateListView.setOnItemClickListener((parent, view, position, id) -> {
            cleanSearchText();

            mBinding.cateListView.setItemChecked(position, true);
            mCateAdapter.notifyDataSetChanged();

            int pos = FoodMenu.getInstance().getFoodItemPosition(mCateAdapter.getItem(position));
            if (pos != -1) {
                mLayoutManager.scrollToPositionWithOffset(pos, 0);
            }
        });
        if (mCateAdapter.getCount() > 0) {
            mBinding.cateListView.setItemChecked(0, true);
        }

        // 菜单
        mLayoutManager = new GridLayoutManager(getContext(), Settings.COLUMN_MENU);
        mLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                int type = mBinding.menuRecyclerView.getAdapter().getItemViewType(position);
                return type == MenuAdapter.TYPE_HEADER ? Settings.COLUMN_MENU : 1;
            }
        });
        mBinding.menuRecyclerView.setLayoutManager(mLayoutManager);

        mMenuAdapter = new MenuAdapter(FoodMenu.getInstance().getAllFoodItem(), this);
        mBinding.menuRecyclerView.setAdapter(mMenuAdapter);

        // 底部购物车按钮
        mBinding.cartButton.setOnClickListener(v -> {
            OrderList.getInstance().refreshData(list -> {
                if (ChoiceType.SCAN == Settings.CHOICE_TYPE) {
                    if (mOnClickListener != null) {
                        mOnClickListener.onOrderClick();
                    }
                } else {
                    if (list.size() > 0) {
                        if (mOnClickListener != null) {
                            mOnClickListener.onOrderClick();
                        }
                    } else {
                        EventBus.getDefault().post(new ToastEvent("请先下单"));
                    }
                }
            });
        });

        if (OrderMode.COMMIT == Settings.ORDER_MODE || ChoiceType.SCAN == Settings.CHOICE_TYPE) {
            mBinding.restartView.setVisibility(View.GONE);
        } else {
            mBinding.restartView.setVisibility(View.VISIBLE);
            mBinding.restartView.setOnClickListener(v -> {

                PromptDialogFragment fragment = PromptDialogFragment.newInstance(
                        "重新点餐?", false);
                fragment.setOnBtnClickListener(new PromptDialogFragment.OnBtnClickListener() {
                    @Override
                    public void onCancelBtnClick() {
                    }

                    @Override
                    public void onOkBtnClick() {
                        Intent intent = new Intent(getContext(), WelcomeActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                    }
                });
                //noinspection ConstantConditions
                fragment.show(getFragmentManager(), null);
            });
        }

        return mBinding.getRoot();
    }

    @Override
    public void onStart() {
        super.onStart();
        OrderList.getInstance().addObserver(mOrderListObserver);
        FoodMenu.getInstance().addObserver(mCateObserver);
        FoodMenu.getInstance().addObserver(mMenuObserver);
        OrderList.getInstance().refreshData(null);

        cleanSearchText();
    }

    @Override
    public void onResume() {
        super.onResume();
        mBinding.menuRecyclerView.addOnScrollListener(mOnScrollListener);
    }

    @Override
    public void onPause() {
        super.onPause();
        mBinding.menuRecyclerView.removeOnScrollListener(mOnScrollListener);
    }

    @Override
    public void onStop() {
        super.onStop();
        OrderList.getInstance().deleteObserver(mOrderListObserver);
        FoodMenu.getInstance().deleteObserver(mCateObserver);
        FoodMenu.getInstance().deleteObserver(mMenuObserver);
    }

    // 菜单点击
    @Override
    public void onFoodItemClick(FoodImpl food, ImageView imageView) {

        if (food instanceof Single) {
            // 单品
            Single single = (Single) food;

            if (single.hasPresentOrAddPrice()) {
                // 有赠送、加价促销项、必选口味
                if (mOnClickListener != null) {
                    mOnClickListener.onSingleOrMealGroupClick(single);
                }

            } else {
                // 只有一个单品，直接添加单品
                addSingle(single, imageView);
            }

        } else if (food instanceof SingleAndMeals) {
            // 单品和套餐
            SingleAndMeals singleAndMeals = (SingleAndMeals) food;

            if (mOnClickListener != null) {
                mOnClickListener.onSingleOrMealGroupClick(singleAndMeals);
            }

        } else if (food instanceof SingleGroup) {
            // 单品组
            SingleGroup singleGroup = (SingleGroup) food;

            if (mOnClickListener != null) {
                mOnClickListener.onSingleGroupClick(singleGroup);
            }
        } else if (food instanceof Meal) {
            //
            Meal meal = (Meal) food;

            if (mOnClickListener != null) {
                mOnClickListener.onMealClick(meal);
            }
        }
    }

    private void addSingle(Single single, ImageView iv) {
        if (iv != null) {
            int[] outLocation = new int[2];
            mBinding.cartCenterView.getLocationInWindow(outLocation);

            if (getActivity() != null) {
                AnimHelper.getInstance().start(getActivity().getWindow(), iv, outLocation);
            }
        }

        EventBus.getDefault().post(new ToastEvent(single.getName() + " +1"));
        OrderList.getInstance().addSingle(single, null, null);
    }

    private void cleanSearchText() {
        if (mBinding.searchEditText.getText().length() > 0) {
            mBinding.searchEditText.setText(null);
        }
    }

    private OnClickListener mOnClickListener;

    public void setOnClickListener(OnClickListener onClickListener) {
        mOnClickListener = onClickListener;
    }

    public interface OnClickListener {

        void onSingleGroupClick(SingleGroup singleGroup);

        void onSingleOrMealGroupClick(Single single);

        void onSingleOrMealGroupClick(SingleAndMeals singleAndMeals);

        void onMealClick(Meal meal);

        /**
         * 点击购物车
         */
        void onOrderClick();
    }
}
